package com.liang.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.liang.pojo.Role;
import com.liang.pojo.User;
import com.liang.service.role.RoleServiceImpl;
import com.liang.service.user.UserServiceImpl;
import com.liang.util.Constant;
import com.liang.util.PageSupport;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("pwdmodify")) {
            checkPassword(req, resp);
        } else if (method.equals("savepwd")) {
            changPassword(req, resp);
        } else if (method.equals("query")) {
            query(req, resp);
        } else if (method.equals("deluser")) {
            deluser(req, resp);
        } else if (method.equals("view")) {
            viewUser(req,resp);
        } else if (method.equals("getrolelist")) {
            getRoleList(req,resp);
        } else if (method.equals("ucexist")) {
            checkUcexist(req,resp);
        }else if (method.equals("add")){
            insertUser(req,resp);
        }else if(method.equals("modify")){
//            进入编辑页面
            modifyView(req,resp);
        }else if (method.equals("modifyexe")){
            submitUpdateUser(req,resp);
        }
    }

    /**
     * 旧密码校验
     */
    public static void checkPassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User attribute = (User) req.getSession().getAttribute(Constant.USER_SESSION);
        String userPassword = attribute.getUserPassword();
        String oldpassword = req.getParameter("oldpassword");


//        万能map
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (attribute == null) {
            resultMap.put("result", "sessionerror");
        } else if (userPassword.equals(oldpassword)) {
            resultMap.put("result", "true");
        } else if (StringUtils.isNullOrEmpty(oldpassword)) {
            resultMap.put("result", "error");
        } else {
            resultMap.put("result", "false");
        }
//        设置返回格式
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
//        JSONArray阿里的工具类，转换格式
        writer.println(JSONArray.toJSONString(resultMap));
        writer.flush();//刷新
        writer.close();//关闭流
    }

    /**
     * 修改密码
     */
    public static void changPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String password = req.getParameter("newpassword");
        User user = (User) req.getSession().getAttribute(Constant.USER_SESSION);


        UserServiceImpl userService = new UserServiceImpl();

        if (user != null && !StringUtils.isNullOrEmpty(password)) {
            Integer id = user.getId();
            Boolean b = userService.updatePassword(password, id);
            if (b) {
                req.setAttribute(Constant.Message, "修改密码成功，请退出登录，使用新密码登录");
                req.getSession().removeAttribute(Constant.USER_SESSION);
            } else {
                req.setAttribute(Constant.Message, "服务器错误，修改密码失败");
            }
        } else {
            req.setAttribute(Constant.Message, "新密码有问题");
        }
        req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req, resp);
    }


    /**
     * 获取用户列表、用户总数、角色列表
     *
     * @param req
     * @param resp
     * @throws IOException
     * @throws ServletException
     */
    public static void query(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        int currentPageNo = 1;
        int pageSize = 5;
        int userRole = 0;
        int total = 0;
        String queryname = req.getParameter("queryname");
        String queryUserRole = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        if (!StringUtils.isNullOrEmpty(queryUserRole)) {
            userRole = Integer.parseInt(queryUserRole);
        }
        if (!StringUtils.isNullOrEmpty(pageIndex)) {
            currentPageNo = Integer.parseInt(pageIndex);
        }

//        用户部分操作
        UserServiceImpl userService = new UserServiceImpl();
//        获取用户分页列表
        List<User> userList = userService.getUserList(queryname, userRole, currentPageNo, pageSize);
//        获取用户总数
        total = userService.getCount(queryname, userRole);
//        缓存分页数据
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(total);
        pageSupport.setTotalPageCountByRs();
//      防止页数引起bug
        int MaxPageNo = pageSupport.getTotalPageCount();
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > MaxPageNo) {
            currentPageNo = MaxPageNo;
        }

//        角色部分操作====>获取角色列表
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList(null, null);
//      输出数据显示
        req.setAttribute("queryUserRole", userRole);
        req.setAttribute("roleList", roleList);
        req.setAttribute("userList", userList);
        req.setAttribute("totalCount", total);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", MaxPageNo);
        req.setAttribute("queryUserName", queryname);

        req.getRequestDispatcher("userlist.jsp").forward(req, resp);
    }

    //    删除用户
    public static void deluser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Boolean flag = false;
        Integer uid = Integer.valueOf(req.getParameter("uid"));
        UserServiceImpl userService = new UserServiceImpl();
        flag = userService.deleteUser(uid);
        HashMap<String, String> params = new HashMap<>();
        if(flag){
            params.put("delResult", "true");
        }else {
            params.put("delResult", "false");
        }

        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
//        JSONArray阿里的工具类，转换格式
        writer.println(JSONArray.toJSONString(params));

        writer.flush();//刷新
        writer.close();//关闭流


    }

    /**查看用户详情信息
     * 根据ID
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public static void viewUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uid = req.getParameter("uid");
        Integer id = -1;
        if(!StringUtils.isNullOrEmpty(uid)){
             id = Integer.valueOf(uid);
        }
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.getUserInfoForId(id);
        req.setAttribute("user",user);
        req.getRequestDispatcher("userview.jsp").forward(req,resp);
    }

//    添加用户页面，获取用户列表
    public static void getRoleList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList(null, null);
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.println(JSONArray.toJSONString(roleList));
        writer.flush();
        writer.close();
    }

//    检查用户编码是否已存在
    public static void checkUcexist(HttpServletRequest req,HttpServletResponse resp){
        User user = null;
        String userCode = req.getParameter("userCode");

        UserServiceImpl userService = new UserServiceImpl();
        user = userService.login(userCode);

        try {
            HashMap<String, String> resultMap = new HashMap<>();
            resp.setContentType("application/json");
//            判断当前userCode是否已存在用户
            if(user != null){
                resultMap.put("userCode","exist");
            }else {
                resultMap.put("userCode","notExist");
            }
            PrintWriter writer = resp.getWriter();
            writer.println(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
//新增用户
    public static void insertUser(HttpServletRequest req,HttpServletResponse resp) {
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        Integer gender = Integer.valueOf(req.getParameter("gender"));
        String bd = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        Integer userRole = Integer.valueOf(req.getParameter("userRole"));
        try {
            Date creationDate = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date bd_date = simpleDateFormat.parse(bd);
            java.sql.Date birthday = new java.sql.Date(bd_date.getTime());

            HttpSession session = req.getSession();
            User userInfo = (User) session.getAttribute(Constant.USER_SESSION);

            if (userInfo!=null){
                Integer createdBy = userInfo.getId();
                UserServiceImpl userService = new UserServiceImpl();
                Boolean flag = userService.insertUser(userCode, userName, userPassword, gender, birthday, phone, address, userRole, createdBy, creationDate);
                if (flag){
                    resp.sendRedirect("user.do?method=query");
                }else {
                    req.setAttribute(Constant.Message,"提交失败");
                    req.getRequestDispatcher("useradd.jsp").forward(req,resp);
                }

            }
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

    }

//    查询用户信息并跳转编辑页面
    public static void modifyView(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uid = req.getParameter("uid");
        Integer id = -1;
        if(!StringUtils.isNullOrEmpty(uid)){
            id = Integer.valueOf(uid);
        }
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.getUserInfoForId(id);
        req.setAttribute("user",user);
        req.getRequestDispatcher("usermodify.jsp").forward(req,resp);
    }

    public static void submitUpdateUser(HttpServletRequest req, HttpServletResponse resp){

        Integer id = Integer.valueOf(req.getParameter("uid"));
        String userName = req.getParameter("userName");
        Integer gender = Integer.valueOf(req.getParameter("gender"));
        String bd = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        Integer userRole = Integer.valueOf(req.getParameter("userRole"));
        try {

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date birthday = simpleDateFormat.parse(bd);
            HttpSession session = req.getSession();
            User user = (User) session.getAttribute(Constant.USER_SESSION);
            Integer modifyBy = user.getId();
            Date modifyDate = new Date();

            UserServiceImpl userService = new UserServiceImpl();
            Boolean flag = userService.modifyUser(id, userName, gender, birthday, phone, address, userRole, modifyBy, modifyDate);

            if(flag){
                resp.sendRedirect("user.do?method=query");
            }else {
                req.setAttribute(Constant.Message,"修改失败");
                req.getRequestDispatcher("user.do?method=modify&uid="+id).forward(req,resp);
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }


}
